import { MathPoint } from "~/models/Math/MathPoint";
import { ISlot } from "./slot/instance";
import type { INode } from "./node/instance";
import { oGraph, Graph } from "./graph";
import type { VarInit } from "../data/var_init";

/**
 * Trainer Graph Editor Bus
 * 编辑器通信总线
 */
class EditorBus {
    /**
     * 
     * REGION CONNECT
     * 以下区域负责图的连接辅助功能
     * 
     */
    pendingSlot?: ISlot
    pendingSlotPoint?: MathPoint

    clearPending() {
        delete this.pendingSlot
        delete this.pendingSlotPoint
    }

    /**
     * 槽被点击时调用的函数
     * @param slot 被点击的槽
     * @param point 经过校正后的槽中心点
     */
    public slotClicked(slot: ISlot, point: MathPoint) {
        
        if (this.pendingSlot) {
            if (this.pendingSlot !== slot) {
                this.pendingSlot.connect(slot)
            }

            // 不管是点击自己两次，还是建立新连接。都清除pending状态。
            this.clearPending()
        }
        else {
            this.pendingSlot = slot
            this.pendingSlotPoint = point
        }
        
    }

    /**
     * 
     * REGION CONNECT END
     * 
     */


    /**
     * 节点的选中和删除
     */
    activeNode?: INode

    deleteActiveNode() {
        if (this.activeNode) {
            // 寻找到前后节点，断连
            const slots = this.activeNode.slots
            slots.forEach(slot => {
                slot.disconnect()
            })

            // 从图中移除
            remove(oGraph.value!.nodesId, x => x === this.activeNode!.id)
            oGraph.value!.nodesId = oGraph.value!.nodesId
            

            // 后处理
            this.activeNode = undefined
        }
    }

    /**
     * 链接的选中和删除
     */
    public activeLinkIndex = -1

    /**
     * 坐标转换
     */
    public rootElement?: HTMLElement
    toLocal(globalPosition: MathPoint): MathPoint {
        const r = this.rootElement!.getBoundingClientRect()
        return new MathPoint(globalPosition.x - r.x, globalPosition.y - r.y)
    }


    /**
     * 参数编辑相关
     */
    isParamEditShown = false
    paramEditTarget?: Graph
    public editParam(Graph?: Graph) {
        this.paramEditTarget = Graph
        this.isParamEditShown = true
    }
    // public editParamFinish() {
    //     this.isParamEditShown = false
    // }

    /**
     * 局部变量编辑相关
     */
    isLocalEditShown = false
    localEditTarget?: VarInit
    public editLocal(localvar?: VarInit) {
        this.localEditTarget = localvar
        this.isLocalEditShown = true
    }
    // public editLocalFinish() {
    //     this.isLocalEditShown = false
    // }
}

export const oBus = ref(new EditorBus())
